#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>

// 求平方和
int square_sum(int n)
{
    sleep(1);
    return n * n;
}
void *pthread_fun(void *arg)
{
    int n = *(int *)arg;
    int *result = malloc(sizeof(int));
    *result = square_sum(n);
    sleep(1);
    pthread_exit(result);
}
int main()
{
    int arr[5] = {1, 2, 3, 4, 5};
    int ret[5];

    // 计时
    struct timeval start, end;
    gettimeofday(&start, NULL);

    // 创建5个线程
    pthread_t tids[5];
    for (int i = 0; i < 5; i++)
    {
        pthread_create(&tids[i], NULL, pthread_fun, &arr[i]);
    }

    // 等待所有线程结束
    for (int i = 0; i < 5; i++)
    {
        void *result = NULL;
        pthread_join(tids[i], &result);
        ret[i] = *(int *)result;
    }
    gettimeofday(&end, NULL);
    // 输出时间
    printf("time used :%ld sec \n",end.tv_sec-start.tv_sec);

    // 累加平方和
    int sum = 0;
    for (int i = 0; i < 5; i++)
    {
        sum += ret[i];
    }
    printf("sum = %d\n", sum);
    return 0; 
}
